# encoding=utf8
import numpy as np
import pandas as pd
from sklearn.linear_model import Perceptron

# 构建感知机算法


class Perceptron(object):
    def __init__(self, learning_rate=0.01, max_iter=200):
        self.lr = learning_rate
        self.max_iter = max_iter

    def fit(self, data, label):
        '''
        input:data(ndarray):训练数据特征
              label(ndarray):训练数据标签
        output:w(ndarray):训练好的权重
               b(ndarry):训练好的偏置
        '''
        # 编写感知机训练方法，w为权重，b为偏置
        self.w = np.array([1.]*data.shape[1])
        self.b = np.array([1.])
        w = np.hstack((self.w, self.b))
        iters = 0

        while iters < self.max_iter:
            incorrect_num = 0

            for x, y in zip(data, label):
                x = np.hstack((x, np.array([1.])))
                if y * w.dot(x) <= 0:
                    w += y * x * self.lr
                    incorrect_num += 1

            if incorrect_num == 0:
                break

            iters += 1

        self.w, self.b = np.hsplit(w, [-1])

    def predict(self, data):
        '''
        input:data(ndarray):测试数据特征
        output:predict(ndarray):预测标签
        '''
        predict = np.array(
            [1 if self.w.dot(d) + self.b > 0 else -1 for d in data])
        return predict


if __name__ == "__main__":
    # data = np.array([[3, 3], [4, 2], [1, 0], [0, 1]])
    # label = np.array([1, 1, -1, -1])
    # md = Perceptron()
    # md.fit(data, label)
    # print(md.predict(np.array([[0, 0], [5, 5]])))

    # print(os.listdir("./step2"))

    # with open("./step2/test_data.csv") as f:
    #     ss = f.readlines()
    #     r = ""
    #     for s in ss:
    #         r += s
    #     print(r)

    with open('感知机\第1关：感知机 - 西瓜好坏自动识别.py', encoding='utf-8') as f:
        code = f.read()
        # hash_name = ['正', '确', '率', '大', '于', '0', '.', '8']
        hash_name = []
        hash_count = [0]*len(hash_name)
        for i, name in enumerate(hash_name):
            if name in code:
                hash_count[i] = 1

        if np.array(hash_count).sum() == 8:
            print('切勿投机取巧！')
        else:

            # 加载数据
            x_train = pd.read_csv('感知机/train_data.csv')
            x_train = np.array(x_train)
            x_test = pd.read_csv('感知机/test_data.csv')
            x_test = np.array(x_test)
            y_train = pd.read_csv('感知机/train_label.csv')
            y_train = y_train['target']
            y_train = y_train.values
            y_test = pd.read_csv('感知机/test_label.csv')
            y_test = y_test['result']
            y_test = y_test.values
            clf = Perceptron()
            clf.fit(x_train, y_train)

            predict = clf.predict(x_test)

        acc = np.mean(predict == y_test)

        if acc > 0.8:
            print('正确率大于0.8')
        else:
            print('正确率为:%.3f请修改' % acc)
